﻿using Bot.Domain.Bot;
using Bot.Domain.Entities;
using Bot.Domain.Interfaces;
using Google.Apis.Auth.OAuth2;
using System;
using System.Threading.Tasks;

namespace Bot.Domain.DialogFlow
{
    public interface ITokenService
    {
        Task<string> GetToken(int siteId, Guid botId);
        Task<string> GetToken(string credJson);
    }
    public class TokenService: ITokenService
    {
        private bool Debug { get; } = false;      

        private IDialogflowDomainService _dialogflowDomainService;

        public TokenService(IDialogflowDomainService dialogflowDomainService)
        {
            _dialogflowDomainService = dialogflowDomainService;
#if DEBUG
            Debug = true;
#endif
        }

        public async Task<string> GetToken(string credJson)
        {
            string json = credJson;

            GoogleCredential credential = GoogleCredential.FromJson(json).CreateScoped("https://www.googleapis.com/auth/cloud-platform");
            
            if (Debug)
            {
                return string.Format("ya29.c.ElrCBbGZNiNxby9TDsQ9h2qRDknVFREhurG5pQC7CqHIMqusVYu24DmwNzjR5Zd30");
            }
            else
            {
                return await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
            }
        }
        public async Task<string> GetToken(int siteId, Guid botId)
        {
            string key = Utils.GenerateDialogflowKey(siteId, botId);

            if (!GoogleCredentialDic.credentialJsonDic.ContainsKey(key))
            {
                Dialogflow botDialogflowDto = _dialogflowDomainService.GetBySiteIdAndBotId(siteId,botId);
                if (botDialogflowDto != null)
                {
                    string value = botDialogflowDto.ProjectAuthJson;
                    GoogleCredentialDic.credentialJsonDic.TryAdd(key, value);
                }
                else
                {
                    throw new Exception("BotDialogFlow table not exists item.");
                }
            }

            //LogHelper.Debug(JsonConvert.SerializeObject(GoogleCredentialDic.credentialJsonDic));

            string json = GoogleCredentialDic.credentialJsonDic[key];
            GoogleCredential credential = GoogleCredential.FromJson(json).CreateScoped("https://www.googleapis.com/auth/cloud-platform");

            if (Debug)
            {
                return string.Format("ya29.c.ElrCBbGZNiNxby9TDsQ9h2qRDknVFREhurG5pQC7CqHIMqusVYu24DmwNzjR5Zd30");
            }
            else
            {
                return await credential.UnderlyingCredential.GetAccessTokenForRequestAsync();
            }
        }
    }
}
